import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as Global from '../TS/Global';
import * as Mycss from "../CSS/mycss.css";
import * as MyCfg from './MyCfg';
import * as Loading from './Loading';

export interface LoginProps extends Global.Myprops {
    ttxx?: string
};

interface LoginState {
    User?: string;
    PWD?: string;
    ErrorStr?: string;
    IsSave?: boolean;
    Language?: string;
};

export class Login extends React.Component<LoginProps,
    LoginState> {
    constructor(props) {
        super(props);
        let issave: boolean;

        if ($.cookie('IsSave') && $.cookie('IsSave') == "true") {
            issave = true;
        }
        //设置状态
        this.state = {
            User: issave && $.cookie('User')
                ? $.cookie('User')
                : "admin",
            PWD: issave && $.cookie('PWD')
                ? $.cookie('PWD')
                : "admin",
            Language: $.cookie('Language')
                ? $.cookie('Language')
                : "zh",
            IsSave: issave
                ? issave
                : false
            // secondsElapsed: 0
        };
        Global.SetLocalType(this.state.Language);
    }
    //用于处理收到的数据
    ReciveMsgEvent(source: any, cmd: string, obj?: any, ...args) {
        if (cmd == 'update') {
            this.forceUpdate();
        } else { }
    }

    //下一步进行显示 进行初始化
    componentDidMount() {
        //类似window.onload
        this.setState((prv, prop) => ({
            // count: this.state.count + 1
        }));

    }
    componentWillReceiveProps(nextProps) {
        //每次父控件重新绘制,赋值新的props触发
        this.setState({});
    }
    public handleClick(e: React.MouseEvent<any>): void {

        e.preventDefault();
        $(this.refs.loginbtn).button('loading');
        if (this.state.IsSave) {
            $.cookie('Language', this.state.Language, { expires: 720 });
            $.cookie('IsSave', this.state.IsSave, { expires: 720 });
            $.cookie('User', this.state.User, { expires: 720 });
            $.cookie('PWD', this.state.PWD, { expires: 720 });
        }

        //发送命令
        // $.cookie('Islogined', true);
        // this
        //     .props
        //     .OnMessageSendEvent(this, "", "loginok", "");
        this.GetCfg({ cmd: 'Login', User: this.state.User, PWD: this.state.PWD });
    }
    //处理页面变换
    public handleChange(event: any): void {

        let tcfg: any = {};
        let value: any;
        let isset: boolean = false;
        if (event.target.type == "checkbox") {

            value = event.target.checked;
            tcfg[event.target.name] = event.target.checked;

            isset = true;
        } else if (event.target.type == "radio") {
            if (event.target.checked) {

                tcfg[event.target.name] = event.target.value;
                isset = true;
            }

        } else if (event.target.type == "select-one") {
            // <option value='0'>全部</option>
            var index = event.target.selectedIndex;
            value = event.target.options[index].value;

        } else {
            value = event.target.value;
        }
        if (!isset) {

            tcfg[event.target.name] = value;
        }
        if (event.target.name == "Language") {
            $.cookie('Language', value, { expires: 720 });
            Global.SetLocalType(value);

        } else if (event.target.name == "IsSave") {
            $.cookie('IsSave', value, {
                expires: 720,
                path: '/'
            });
            console.log("保存配置");
        }

        this.setState(tcfg, () => { MyCfg.InitMemu(); this.forceUpdate() });

    }

    GetCfg(data: any): void {
        console.log("登录...");
        let promise = new Promise(function (resolve, reject) {

            $.ajax({
                url: "WebService.cgi",

                type: 'post',
                error: (xhr, status, error) => {

                    reject(error);
                },
                contentType: "application/x-www-form-urlencoded",
                data: {
                    datafrom: 'common',
                    jsondata: JSON.stringify(data)
                },
                dataType: "json",
                // dataType: "jsonp", // jsonp: "callback", jsonpCallback:
                // "success_jsonpCallback",
                success: (result) => {
                    resolve(result);
                }
            });
        });
        promise.then((results: any) => {
            console.log("获取数据成功");
            $(this.refs.loginbtn).button('reset');
            if (results['result'] == "ok!") {
                console.log("得到返回值");
                $.cookie('Islogined', true);
                this
                    .props
                    .OnMessageSendEvent(this, "", "loginok", "");
            } else {

                this.setState({ ErrorStr: Global.GetLocal("用户名或密码错误") });
            }
            this.forceUpdate();
            // MyCfg.tc = 1; MyCfg.mycfg.Net_cfg = results.Net_cfg; MyCfg.mycfg.Serial_cfg =
            // results.Serial_cfg;
            console.log(results)
        }).catch((errors) => {
            $(this.refs.loginbtn).button('reset');
            console.log("获取数据失败" + errors);
            this.setState({
                ErrorStr: Global.GetLocal("验证出现异常")
            });
        });
    }
    public render(): JSX.Element {
        let errorview = <div className="alert alert-danger" role="alert">{this.state.ErrorStr}</div>;

        return (
            <div className={Mycss.Center_flex}>

                <form
                    action=""
                    method="POST"
                    className="form-horizontal col-xs-10 col-sm-7 col-lg-5"
                    role="form">
                    <div className="form-group">
                        <h1 className="text-center">
                            {Global.GetLocal("标题名称")}
                        </h1>
                    </div>
                    <div className="form-group">
                        <label className="col-xs-2 control-label">
                            {Global.GetLocal("用户名")}
                        </label>
                        <div className="col-xs-8">
                            <input
                                type="text"
                                name="User"
                                className="form-control"
                                placeholder=" "
                                value={this.state.User}
                                onChange={e => this.handleChange(e)} />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-xs-2 control-label">
                            {Global.GetLocal("密码")}</label>
                        <div className="col-xs-8">
                            <input
                                type="password"
                                name="PWD"
                                className="form-control"
                                placeholder=" "
                                value={this.state.PWD}
                                onChange={e => this.handleChange(e)} />
                        </div>
                    </div>
                    <div className="form-group  ">

                        <label className="col-xs-2 control-label">语言(Language)</label>
                        <div className="col-xs-8">

                            <select
                                className="form-control"
                                name="Language"
                                value={this.state.Language}
                                onChange={e => this.handleChange(e)}>
                                <option value="zh">中文(Chinese)</option>
                                <option value="en">英文(English)</option>
                            </select>

                        </div>
                    </div>
                    <div className="form-group">
                        <div className="col-sm-10 col-sm-offset-2  ">

                            <div className="checkbox">
                                <label>
                                    <input
                                        type="checkbox"
                                        name="IsSave"
                                        checked={this.state.IsSave}
                                        onChange={e => this.handleChange(e)} /> {Global.GetLocal("记住密码")}
                                </label>
                            </div>

                        </div>
                    </div>
                    <div className="form-group">
                        <div className="col-sm-10 col-sm-offset-2  ">

                            <button
                                ref="loginbtn"
                                type="submit"
                                data-loading-text="登录中..."
                                className="btn btn-primary"
                                onClick={e => this.handleClick(e)}>
                                {Global.GetLocal("登录")}</button>
                        </div>
                    </div>
                    <div className="form-group">
                        {this.state.ErrorStr
                            ? errorview
                            : ''}

                    </div>

                </form>

            </div>
        );
    }
}